package game;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;


public class Log extends JFrame {

	
	public String puname;
	public static void main(String[] args) {
		Log frameTabel = new Log();
	}

	JButton blogin = new JButton("Login");
	JPanel panel = new JPanel();
	JTextField txuser = new JTextField(15);
	JPasswordField pass = new JPasswordField(15);

	Log() {
		super("Login Autentification");
		setSize(300, 200);
		setLocation(500, 280);
		panel.setLayout(null);

		txuser.setBounds(70, 30, 150, 20);
		pass.setBounds(70, 65, 150, 20);
		blogin.setBounds(110, 100, 80, 20);

		panel.add(blogin);
		panel.add(txuser);
		panel.add(pass);

		getContentPane().add(panel);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		actionlogin();
	}

	public void actionlogin() {
		blogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				puname = txuser.getText();
				String ppaswd = pass.getText();
				Reader reader = null;
				try {
					int data;
            BufferedReader br = new BufferedReader(new FileReader(puname + ".txt"));
				    try {
				        StringBuilder sb = new StringBuilder();
				        String line = br.readLine();

				        if (line != null) {
				            sb.append(line);
				            line = br.readLine();
				        }
				        String name = sb.toString();
				        if(ppaswd.equals(name)){
							Game regFace = new Game();
							regFace.setVisible(true);
							regFace.start(puname);
							dispose();
				        } else {
							JOptionPane.showMessageDialog(null,"Wrong Password / Username");
							txuser.setText("");
							pass.setText("");
							txuser.requestFocus();
						}
				    } finally {
				        br.close();
				    }
				}catch (UnsupportedEncodingException e1) {
					JOptionPane.showMessageDialog(null,"Wrong Password / Username");
					txuser.setText("");
					pass.setText("");
					txuser.requestFocus();
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null,"Wrong Password / Username");
					txuser.setText("");
					pass.setText("");
					txuser.requestFocus();
				}
			}
		});
	}

}